package com.kongge.algorithm.demo;

/**
 * 乘方
 * @author gaoshiqi
 *
 */
public class Power implements IAlgorithm {

	public void execute() {
		try {
			int base = 0;
			int exponent = -1;
			double result = getPowerNumber(base, exponent);
			System.out.println(base + " 的 " + exponent + " 次方为 " + result);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	private double getPowerNumber(double base, int exponent) throws Exception{
		if (base == 0d && exponent < 0) {
			throw new Exception("基数为0时，乘方不能为负数");
		}
		double result = 0;
		if (exponent < 0) {
			result = powerNumber(base, exponent * -1);
			result = 1 / result;
		} else {
			result = powerNumber(base, exponent);
		}
		return result;
	}
	
	private double powerNumber(double base, int exponent) {
		if (exponent == 1) {
			return base;
		}
		double result = 0;
		result = powerNumber(base, exponent / 2) * powerNumber(base, exponent / 2);
		// 奇数
		if ((exponent & 1) == 1) {
			result *= base;
		}
		return result;
	}

}
